// 全局变量
let currentProvider = null;
let currentModel = null;
let uploadedFile = null;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    loadProviders();
    setupEventListeners();
});

// 加载AI提供商
async function loadProviders() {
    try {
        const response = await axios.get('/api/providers');
        const providers = response.data;
        
        const providerSelect = document.getElementById('providerSelect');
        providerSelect.innerHTML = '<option value="">请选择AI提供商</option>';
        
        Object.entries(providers).forEach(([key, provider]) => {
            const option = document.createElement('option');
            option.value = key;
            option.textContent = provider.name;
            option.dataset.models = JSON.stringify(provider.models);
            providerSelect.appendChild(option);
        });
        
    } catch (error) {
        console.error('加载AI提供商失败:', error);
        showError('加载AI提供商失败，请刷新页面重试');
    }
}

// 设置事件监听器
function setupEventListeners() {
    // 提供商选择变化
    document.getElementById('providerSelect').addEventListener('change', handleProviderChange);
    
    // 模型选择变化
    document.getElementById('modelSelect').addEventListener('change', handleModelChange);
    
    // 文件上传
    document.getElementById('fileInput').addEventListener('change', handleFileUpload);
    
    // 生成按钮
    document.getElementById('generateBtn').addEventListener('click', handleGenerate);
    
    // 清空按钮
    document.getElementById('clearBtn').addEventListener('click', handleClear);
    
    // 复制按钮
    document.getElementById('copyBtn').addEventListener('click', handleCopy);
    
    // 输入框变化
    document.getElementById('promptInput').addEventListener('input', validateForm);
}

// 处理提供商选择变化
function handleProviderChange(event) {
    const providerSelect = event.target;
    const modelSelect = document.getElementById('modelSelect');
    
    if (providerSelect.value) {
        const selectedOption = providerSelect.selectedOptions[0];
        const models = JSON.parse(selectedOption.dataset.models);
        
        modelSelect.innerHTML = '<option value="">请选择模型</option>';
        models.forEach(model => {
            const option = document.createElement('option');
            option.value = model;
            option.textContent = model;
            modelSelect.appendChild(option);
        });
        
        modelSelect.disabled = false;
        currentProvider = providerSelect.value;
    } else {
        modelSelect.innerHTML = '<option value="">请先选择提供商</option>';
        modelSelect.disabled = true;
        currentProvider = null;
    }
    
    validateForm();
}

// 处理模型选择变化
function handleModelChange(event) {
    currentModel = event.target.value;
    validateForm();
}

// 处理文件上传
async function handleFileUpload(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    const formData = new FormData();
    formData.append('file', file);
    
    try {
        const response = await axios.post('/api/upload', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        });
        
        uploadedFile = response.data.file;
        document.getElementById('fileInfo').innerHTML = `
            <i class="fas fa-file"></i> 
            ${uploadedFile.originalname} 
            <span class="text-muted">(${formatFileSize(uploadedFile.size)})</span>
        `;
        
        validateForm();
    } catch (error) {
        console.error('文件上传失败:', error);
        showError('文件上传失败，请重试');
    }
}

// 处理生成
async function handleGenerate() {
    const prompt = document.getElementById('promptInput').value.trim();
    
    if (!currentProvider || !currentModel || (!prompt && !uploadedFile)) {
        showError('请填写完整信息');
        return;
    }
    
    // 显示加载状态
    showLoading(true);
    hideResult();
    
    try {
        const response = await axios.post('/api/generate', {
            provider: currentProvider,
            model: currentModel,
            prompt: prompt || `请分析上传的文件：${uploadedFile.originalname}`,
            type: uploadedFile ? 'file' : 'text'
        });
        
        displayResult(response.data.data);
    } catch (error) {
        console.error('AI生成失败:', error);
        showError(error.response?.data?.error || 'AI服务调用失败');
    } finally {
        showLoading(false);
    }
}

// 处理清空
function handleClear() {
    document.getElementById('promptInput').value = '';
    document.getElementById('fileInput').value = '';
    document.getElementById('fileInfo').innerHTML = '';
    uploadedFile = null;
    hideResult();
    validateForm();
}

// 处理复制
function handleCopy() {
    const resultContent = document.getElementById('resultContent').textContent;
    navigator.clipboard.writeText(resultContent).then(() => {
        const btn = document.getElementById('copyBtn');
        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-check"></i> 已复制';
        setTimeout(() => {
            btn.innerHTML = originalText;
        }, 2000);
    }).catch(err => {
        console.error('复制失败:', err);
        showError('复制失败，请手动复制');
    });
}

// 验证表单
function validateForm() {
    const prompt = document.getElementById('promptInput').value.trim();
    const generateBtn = document.getElementById('generateBtn');
    
    const isValid = currentProvider && currentModel && (prompt || uploadedFile);
    generateBtn.disabled = !isValid;
}

// 显示结果
function displayResult(content) {
    const resultSection = document.getElementById('resultSection');
    const resultContent = document.getElementById('resultContent');
    
    resultContent.textContent = content;
    resultSection.style.display = 'block';
    
    // 滚动到结果区域
    resultSection.scrollIntoView({ behavior: 'smooth' });
}

// 隐藏结果
function hideResult() {
    document.getElementById('resultSection').style.display = 'none';
}

// 显示/隐藏加载状态
function showLoading(show) {
    document.getElementById('loadingSpinner').style.display = show ? 'block' : 'none';
    document.getElementById('generateBtn').disabled = show;
}

// 显示错误
function showError(message) {
    // 创建错误提示
    const alertDiv = document.createElement('div');
    alertDiv.className = 'alert alert-danger alert-dismissible fade show position-fixed';
    alertDiv.style.top = '20px';
    alertDiv.style.right = '20px';
    alertDiv.style.zIndex = '9999';
    alertDiv.style.minWidth = '300px';
    alertDiv.innerHTML = `
        <i class="fas fa-exclamation-triangle"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.parentNode.removeChild(alertDiv);
        }
    }, 3000);
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    // Ctrl+Enter 快速生成
    if (e.ctrlKey && e.key === 'Enter') {
        e.preventDefault();
        const generateBtn = document.getElementById('generateBtn');
        if (!generateBtn.disabled) {
            handleGenerate();
        }
    }
    
    // Ctrl+Shift+C 清空
    if (e.ctrlKey && e.shiftKey && e.key === 'C') {
        e.preventDefault();
        handleClear();
    }
});
